﻿using System;
using System.Net;
using System.Windows;
#if WINDOWS_PHONE
using System.Device.Location;
#elif PocketPC
using Interfaces;
#endif

namespace Transportr
{
    public delegate void LocationChangedHandler();

    public class LocationModel
    {
        private static GeoCoordinateWatcher watcher;
        private static GeoPosition<GeoCoordinate> position;

        public static event LocationChangedHandler LocationChanged;
        public static Map.GeoPoint CurrentLocation
        {
            get
            {
                if (position.Location.IsUnknown)
                    return null;
                return new Map.GeoPoint() {
                    Latitude = position.Location.Latitude,
                    Longitude = position.Location.Longitude};
            }
        }
        public static bool Valid {
            get
            {
//                return !position.Location.IsUnknown && watcher.Status == GeoPositionStatus.Ready;
                return true;
            }
        }

        public static void Initialize()
        {
            /* FOR TESTING */
            position = new GeoPosition<GeoCoordinate>(DateTime.Now, new GeoCoordinate(47.473, 19.047));
            watcher_PositionChanged(null, new GeoPositionChangedEventArgs<GeoCoordinate>(position));
            /* FOR TESTING*/ 

            watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
            watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
            watcher.Start();
        }

        private static void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            position = e.Position;
            if (LocationChanged != null)
            {
                LocationChanged();
            }
        }
    }
}
